Sliding window maximum [Mono Deque]

Time: O(N); Space: O(K); hard

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.

You can only see the k numbers in the window.

Each time the sliding window moves right by one position. Return the max sliding window.

Follow up:

  • Could you solve it in linear time?

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3

Output: [3,3,5,5,6,7]

Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Example 2:

Input: nums = [1,2,3,1,2,3], k = 5 Output: [3,3]

Explanation:

  • At first, the state of the window is as follows: [,2,3,1,2,1 | , 3], a maximum of 3;

  • And then the window to the right one. [1, | 2,3,1,2,3 |], a maximum of 3;

Constraints:

  • 1 <= len(nums) <= 10^5

  • -10^4 <= nums[i] <= 10^4

1. Mono deque

[1]:
from collections import deque

class Solution1(object):
    """
    Time: O(N)
    Space: O(K)
    """
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        result, dq = [], deque()
        for i in range(len(nums)):
            if dq and i-dq[0] == k:
                dq.popleft()
            while dq and nums[dq[-1]] <= nums[i]:
                dq.pop()
            dq.append(i)
            if i >= k-1:
                result.append(nums[dq[0]])
        return result


[3]:
s = Solution1()

nums = [1,3,-1,-3,5,3,6,7]
k = 3
assert s.maxSlidingWindow(nums, k) == [3,3,5,5,6,7]

nums = [1,2,3,1,2,3]
k = 5
assert s.maxSlidingWindow(nums, k) == [3,3]